<div id="employees">
    <div class="tree-wrap">
        <div class="tree-title">{{$t('user.organization')}}</div>
        <div class="tree-search">
            <i-input v-model.trim="sosoValue" icon="ios-close-circle-outline" @on-click="cleanSosoVal"></i-input>
        </div>
        <div class="employees-tree-box">
            <Tree :data="treeData"></Tree>
        </div>
    </div>
    <div class="table-wrap">
        <div class="table-title">{{$t('user.listEmployees')}}</div>
        <div class="table-action">
            <div style="width: 200px;">
                <i-input v-model.trim="sosoTableValue" icon="ios-close-circle-outline" @on-click="cleanSearchVal"></i-input>
            </div>
            <div>
                <i-button @click="queryEmployees">{{$t('videoback.search')}}</i-button>
            </div>
            <div>
                <i-button type='primary' @click="showAddModal">{{$t('user.add')}}</i-button>
            </div>
        </div>
        <div class="employees-table-box">
            <i-table :data="tableData" border :loading="loading" :columns="columns" :height="taleHeight"></i-table>
        </div>
    </div>
    <Modal v-model="modal" width="900" :title="modalTitle">
        <div style="width:700px;margin:10px auto">
            <Row style="margin: 10px 0" v-if="isEdit">
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;"><i style="color: red;display: inline-block;">*</i>&nbsp;{{$t("reportForm.selectAccount")}} : &nbsp;</i-col>
                <i-col span="8">
                    <div class="search-wrapper">
                        <i-input v-model.trim="creater" :icon="iconState" @on-change="sosoValueChange" @on-blur="blur" @on-focus="focus" @on-click="focus"></i-input>
                        <transition name="fade">
                            <ul class="search-item-wrapper" v-show="isShowMatchDev" style="cursor: pointer;">
                                <li v-for="item in userlists" style="padding:5px 10px;" @click="selectedCmd(item)" :class="{'ivu-select-item-focus':item == creater}">
                                    <div :value="item" :key="item">
                                        <span style="cursor: pointer;">{{ item }}</span>
                                    </div>
                                </li>
                            </ul>
                        </transition>
                    </div>
                </i-col>
            </Row>
            <Row style="margin: 10px 0">
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t('reportForm.name')}} : &nbsp;</i-col>
                <i-col span="8">
                    <i-input v-model.trim="name"></i-input>
                </i-col>
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t('device.gender')}} : &nbsp;</i-col>
                <i-col span="8">
                    <i-select v-model.sync="sex">
                        <i-option value="1">{{$t('device.man')}}</i-option>
                        <i-option value="0">{{$t('device.girl')}}</i-option>
                    </i-select>
                </i-col>
            </Row>
            <Row style="margin: 10px 0">
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t('user.phone1')}} : &nbsp;</i-col>
                <i-col span="8">
                    <i-input v-model.trim="phone1"></i-input>
                </i-col>
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t('user.phone2')}} : &nbsp;</i-col>
                <i-col span="8">
                    <i-input v-model.trim="phone2"></i-input>
                </i-col>
            </Row>
            <Row style="margin: 10px 0">
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t('user.sosphone1')}} : &nbsp;</i-col>
                <i-col span="8">
                    <i-input v-model.trim="sosphone1"></i-input>
                </i-col>
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t('user.sosphone2')}} : &nbsp;</i-col>
                <i-col span="8">
                    <i-input v-model.trim="sosphone2"></i-input>
                </i-col>
            </Row>
            <Row style="margin: 10px 0">
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t('reportForm.idNumber')}} : &nbsp;</i-col>
                <i-col span="8">
                    <i-input v-model.trim="cardid"></i-input>
                </i-col>
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t('user.certificationcode')}} : &nbsp;</i-col>
                <i-col span="8">
                    <i-input v-model.trim="certificationcode"></i-input>
                </i-col>
            </Row>
            <Row style="margin: 10px 0">
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t('user.agencyname')}} : &nbsp;</i-col>
                <i-col span="8">
                    <i-input v-model.trim="agencyname"></i-input>
                </i-col>
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t('user.certificationvalidatedate')}} : &nbsp;</i-col>
                <i-col span="8">
                    <date-picker type="date" v-model="certificationvalidatedate" style="width: 100%"></date-picker>
                </i-col>
            </Row>
            <Row style="margin: 10px 0">
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t('user.drivercardid')}} : &nbsp;</i-col>
                <i-col span="8">
                    <i-input v-model.trim="drivercardid"></i-input>
                </i-col>
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t('user.driveragencyname')}} : &nbsp;</i-col>
                <i-col span="8">
                    <i-input v-model.trim="driveragencyname"></i-input>
                </i-col>
            </Row>
            <Row style="margin: 10px 0">
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t('user.drivercardtype')}} : &nbsp;</i-col>
                <i-col span="8">
                    <i-input v-model.trim="drivercardtype"></i-input>
                </i-col>
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t('reportForm.address')}} : &nbsp;</i-col>
                <i-col span="8">
                    <i-input v-model.trim="address"></i-input>
                </i-col>
            </Row>
            <Row style="margin: 10px 0">
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t('user.drivercardstartday')}} : &nbsp;</i-col>
                <i-col span="8">
                    <date-picker type="date" v-model="drivercardstartday" style="width: 100%"></date-picker>
                </i-col>
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t('user.drivercardendday')}} : &nbsp;</i-col>
                <i-col span="8">
                    <date-picker type="date" v-model="drivercardendday" style="width: 100%"></date-picker>
                </i-col>
            </Row>
            <Row style="margin: 10px 0">
                <i-col span="6" :offset="7">
                    <i-button style="width: 100%" @click="handleSubmit">{{$t("bgMgr.submit")}}</i-button>
                </i-col>
                <i-col span="6" :offset="1">
                    <i-button style="width: 100%" @click="resetInfo">{{$t("bgMgr.reset")}}</i-button>
                </i-col>
            </Row>
        </div>
        <div slot="footer" style="height:20px;"></div>
    </Modal>
    <script>
        vueInstanse = new Vue({
            el: "#employees",
            i18n: utils.getI18n(),
            data: {
                modal: false,
                loading: false,
                isEdit: false,
                userlists: globalUserList,
                isShowMatchDev: false,
                iconState: "ios-arrow-down",
                columns: [{
                    title: vRoot.$t("bgMgr.action"),
                    key: 'action',
                    width: 140,
                    render: function(h, params) {
                        return h('div', [
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: function() {
                                        editObject = params.row;
                                        vueInstanse.isEdit = true;
                                        vueInstanse.modal = true;
                                        vueInstanse.creater = editObject.creater;
                                        vueInstanse.setEditRowValue(editObject);
                                    }
                                }
                            }, vRoot.$t("bgMgr.edit")),

                            h('Poptip', {
                                props: {
                                    confirm: true,
                                    title: vRoot.$t("message.confirmDel")
                                },
                                style: {
                                    marginRight: '5px',
                                    zIndex: 9999,
                                },
                                on: {
                                    'on-ok': function() {
                                        vueInstanse.handleDelete(params);
                                    }
                                }
                            }, [
                                h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    }
                                }, vRoot.$t("bgMgr.delete"))
                            ]),
                        ]);
                    }
                }, {
                    title: vRoot.$t('user.creater'),
                    key: 'creater',
                    width: 150,
                }, {
                    title: vRoot.$t('reportForm.name'),
                    key: 'name',
                    width: 120,
                }, {
                    title: vRoot.$t('reportForm.updateTime'),
                    width: 110,
                    render: function(h, params) {
                        return h('span', {}, DateFormat.format(new Date(params.row.updatetime), 'yyyy-MM-dd'))
                    },
                }, {
                    title: vRoot.$t('reportForm.idNumber'),
                    key: 'cardid',
                    width: 150,
                }, {
                    title: vRoot.$t("device.gender"),
                    width: 100,
                    render: function(h, params) {
                        return h('span', {}, params.row.sex == 1 ? vRoot.$t("device.man") : vRoot.$t("device.girl"));
                    },
                }, {
                    title: vRoot.$t("user.phone1"),
                    key: 'phone1',
                    width: 150,
                }, {
                    title: vRoot.$t("user.phone2"),
                    key: 'phone2',
                    width: 150,
                }, {
                    title: vRoot.$t("user.sosphone1"),
                    key: 'sosphone1',
                    width: 150,
                }, {
                    title: vRoot.$t("user.sosphone2"),
                    key: 'sosphone2',
                    width: 150,
                }, {
                    title: vRoot.$t("user.certificationcode"),
                    key: 'certificationcode',
                    width: 150,
                }, {
                    title: vRoot.$t("user.agencyname"),
                    key: 'agencyname',
                    width: 150,
                }, {
                    title: vRoot.$t("user.certificationvalidatedate"),
                    key: ' certificationvalidatedate',
                    width: 150,
                }, {
                    title: vRoot.$t("reportForm.address"),
                    key: 'address',
                    width: 150,
                }, {
                    title: vRoot.$t("user.drivercardid"),
                    key: 'drivercardid',
                    width: 150,
                }, {
                    title: vRoot.$t("user.driveragencyname"),
                    key: 'driveragencyname',
                    width: 150,
                }, {
                    title: vRoot.$t("user.drivercardtype"),
                    key: 'drivercardtype',
                    width: 150,
                }, {
                    title: vRoot.$t("user.drivercardstartday"),
                    key: 'drivercardstartday',
                    width: 150,
                }, {
                    title: vRoot.$t("user.drivercardendday"),
                    key: 'drivercardendday',
                    width: 150,
                }],
                treeData: [],
                tableData: [],
                taleHeight: 300,
                sosoTableValue: '',
                createrToUser: userName,
                creater: '',
                sosoValue: '',
                name: '',
                cardid: '',
                sex: '1',
                phone1: '',
                phone2: '',
                sosphone1: '',
                sosphone2: '',
                certificationcode: '',
                agencyname: '',
                certificationvalidatedate: new Date(), //证件有效期
                address: '',
                drivercardid: '',
                driveragencyname: '',
                drivercardtype: '',
                drivercardstartday: new Date(),
                drivercardendday: new Date(),
            },
            methods: {
                cleanSosoVal: function() {
                    if (this.sosoValue != '') {
                        this.sosoValue = '';
                    }
                },
                cleanSearchVal: function() {
                    this.sosoTableValue = '';
                },
                selectedCmd: function(item) {
                    var me = this;
                    setTimeout(function() {
                        me.isShowMatchDev = false;
                        me.creater = item;
                    }, 100)
                },
                sosoValueChange: function() {
                    var me = this;
                    var value = this.creater.toLowerCase();

                    if (this.timeoutIns != null) {
                        clearTimeout(this.timeoutIns);
                    }

                    if (!value.trim()) {
                        this.userlists = globalUserList;
                        return;
                    }

                    this.timeoutIns = setTimeout(function() {
                        var list = [];
                        me.list.forEach(function(itme) {
                            if (itme.toLowerCase().indexOf(value) != -1) {
                                list.push(itme);
                            }
                        })
                        me.userlists = list;
                    }, 100);
                },
                focus: function() {
                    this.isShowMatchDev = true;
                },
                blur: function() {
                    var me = this
                    setTimeout(function() {
                        me.isShowMatchDev = false;
                    }, 300)
                },
                handleDelete: function(params) {
                    var me = this;
                    var index = params.index;
                    var row = params.row;
                    var url = myUrls.deleteEmployees();
                    var data = {
                        employees: [row.employeeid],
                    }
                    utils.sendAjax(url, data, function(resp) {
                        if (resp.status === 0) {
                            me.$delete(me.tableData, index);
                            me.$Message.success(vRoot.$t("message.deleteSucc"));
                        } else {
                            me.$Message.error(vRoot.$t("message.deleteFail"));
                        }
                    });
                },
                setEditRowValue: function(row) {
                    this.name = row.name;
                    this.cardid = row.cardid;
                    this.sex = String(row.sex);
                    this.phone1 = row.phone1;
                    this.phone2 = row.phone2;
                    this.sosphone1 = row.sosphone1;
                    this.sosphone2 = row.sosphone2;
                    this.certificationcode = row.certificationcode;
                    this.agencyname = row.agencyname;
                    this.certificationvalidatedate = new Date(row.certificationvalidatedate); //证件有效期
                    this.address = row.address;
                    this.drivercardid = row.drivercardid;
                    this.driveragencyname = row.driveragencyname;
                    this.drivercardtype = row.drivercardtype;
                    this.drivercardstartday = new Date(row.drivercardstartday);
                    this.drivercardendday = new Date(row.drivercardendday);
                },

                showAddModal: function() {
                    this.isEdit = false;
                    this.setEditRowValue({
                        name: '',
                        cardid: '',
                        sex: '1',
                        phone1: '',
                        phone2: '',
                        sosphone1: '',
                        sosphone2: '',
                        certificationcode: '',
                        agencyname: '',
                        certificationvalidatedate: new Date(), //证件有效期
                        address: '',
                        drivercardid: '',
                        driveragencyname: '',
                        drivercardtype: '',
                        drivercardstartday: new Date(),
                        drivercardendday: new Date(),
                    })
                    this.modal = true;
                },
                calcTableHeight: function() {
                    var wHeight = window.innerHeight;
                    this.taleHeight = wHeight - 150;
                },
                handleSubmit: function() {
                    var me = this;
                    var url = '';
                    var data = {
                        creater: this.createrToUser,
                        name: this.name,
                        cardid: this.cardid,
                        sex: Number(this.sex),
                        phone1: this.phone1,
                        phone2: this.phone2,
                        sosphone1: this.sosphone1,
                        sosphone2: this.sosphone2,
                        certificationcode: this.certificationcode,
                        agencyname: this.agencyname,
                        certificationvalidatedate: DateFormat.format(new Date(this.certificationvalidatedate), 'yyyy-MM-dd'),
                        address: this.address,
                        drivercardid: this.drivercardid,
                        driveragencyname: this.driveragencyname,
                        drivercardtype: this.drivercardtype,
                    };
                    if (this.isEdit) {
                        if (globalUserList.indexOf(this.creater) == -1) {
                            me.$Message.error(me.$t("message.selectCorrectAccount"));
                            return;
                        }
                        url = myUrls.editEmployee();
                        data.employeeid = editObject.employeeid;
                        data.creater = this.creater;
                    } else {
                        url = myUrls.createEmployee();
                    }


                    this.drivercardstartday && (data.drivercardstartday = DateFormat.format(new Date(this.drivercardstartday), 'yyyy-MM-dd'));
                    this.drivercardendday && (data.drivercardendday = DateFormat.format(new Date(this.drivercardendday), 'yyyy-MM-dd'));
                    utils.sendAjax(url, data, function(respData) {
                        if (me.isEdit) {
                            if (respData.status == 0) {
                                if (editObject.creater != respData.creater) {
                                    var index = 0;
                                    me.tableData.forEach(function(item, idx) {
                                        if (item.employeeid == editObject.employeeid) {
                                            index = idx;
                                        }
                                    });
                                    me.$delete(me.tableData, index);
                                } else {
                                    Object.assign(editObject, respData);
                                };
                                me.$Message.success(vRoot.$t("message.changeSucc"));
                                me.modal = false;
                            } else {
                                me.$Message.error(vRoot.$t("message.changeFail"));
                            }
                        } else {
                            if (respData.status == 0) {
                                me.tableData.push(respData);
                                me.$Message.success(vRoot.$t("message.addSucc"));
                                me.modal = false;
                            } else {
                                me.$Message.error(vRoot.$t("message.addFail"));
                            }

                        }
                    });
                },
                resetInfo: function() {
                    this.setEditRowValue({
                        name: '',
                        cardid: '',
                        sex: '1',
                        phone1: '',
                        phone2: '',
                        sosphone1: '',
                        sosphone2: '',
                        certificationcode: '',
                        agencyname: '',
                        certificationvalidatedate: new Date(), //证件有效期
                        address: '',
                        drivercardid: '',
                        driveragencyname: '',
                        drivercardtype: '',
                        drivercardstartday: new Date(),
                        drivercardendday: new Date(),
                    })
                },
                queryUsersTree: function(callback) {
                    var url = myUrls.queryUsersTree(),
                        me = this;
                    utils.sendAjax(url, {
                        username: userName
                    }, function(respData) {
                        if (respData.status == 0 && respData.rootuser.user) {
                            callback([me.castUsersTreeToDevicesTree(respData.rootuser)]);
                        } else {
                            me.$Message.error(me.$t('monitor.queryFail'))
                        }
                    });
                },
                castUsersTreeToDevicesTree: function(devicesTreeRecord) {
                    var me = this;
                    var iViewTree = {
                        render: function(h, params) {
                            var username = params.data.title;
                            return h('span', {
                                on: {
                                    'click': function() {
                                        me.createrToUser = username;
                                        me.queryEmployees();
                                    }
                                },
                                style: {
                                    cursor: 'pointer',
                                    color: (me.createrToUser == username) ? '#2D8CF0' : '#000'
                                }
                            }, [
                                h('span', [
                                    h('Radio', {
                                        props: {
                                            value: username == me.createrToUser
                                        },
                                        style: {
                                            marginRight: '4px',
                                            marginLeft: '4px'
                                        }
                                    }),
                                    h('span', params.data.title)
                                ]),
                            ])
                        },
                        expand: true,
                    };
                    if (devicesTreeRecord != null) {
                        var username = devicesTreeRecord.user.username;
                        var subusers = devicesTreeRecord.subusers;
                        iViewTree.title = username;
                        if (username != null && subusers != null && subusers.length > 0) {
                            var subDevicesTreeRecord = this.doCastUsersTreeToDevicesTree(subusers);
                            iViewTree.children = subDevicesTreeRecord;

                        }
                    }
                    return iViewTree;
                },
                doCastUsersTreeToDevicesTree: function(usersTrees) {
                    var devicesTreeRecord = [],
                        me = this;
                    if (usersTrees != null && usersTrees.length > 0) {
                        for (var i = 0; i < usersTrees.length; ++i) {
                            var usersTree = usersTrees[i];
                            var username = usersTree.user.username;
                            var subusers = usersTree.subusers;
                            var currentsubDevicesTreeRecord = {
                                render: function(h, params) {
                                    var username = params.data.title;
                                    return h('span', {
                                        on: {
                                            'click': function() {
                                                me.createrToUser = username;
                                                me.queryEmployees();
                                            }
                                        },
                                        style: {
                                            cursor: 'pointer',
                                            color: (me.createrToUser == username) ? '#2D8CF0' : '#000'
                                        }
                                    }, [
                                        h('span', [
                                            h('Radio', {
                                                props: {
                                                    value: username == me.createrToUser
                                                },
                                                style: {
                                                    marginRight: '4px',
                                                    marginLeft: '4px'
                                                }
                                            }),
                                            h('span', params.data.title)
                                        ]),
                                    ])
                                },
                            };
                            currentsubDevicesTreeRecord.title = username;
                            if (username != null && subusers != null && subusers.length > 0) {
                                var subDevicesTreeRecord = this.doCastUsersTreeToDevicesTree(subusers);
                                currentsubDevicesTreeRecord.children = subDevicesTreeRecord;
                            }
                            devicesTreeRecord.push(currentsubDevicesTreeRecord);
                        }
                    }
                    return devicesTreeRecord;
                },

                filterMethod: function(value) {
                    if (value == '') {
                        this.treeData = this.groupslist;
                    } else {
                        value = value.toLowerCase();
                        this.treeData = [];
                        this.treeData = this.variableDeepSearch(this.groupslist, value, 5);
                    }
                },
                variableDeepSearch: function(treeDataFilter, searchWord, limitcount) {
                    var childTemp = [];
                    var that = this;
                    for (var i = 0; i < treeDataFilter.length; i++) {
                        var copyItem = null;
                        var item = treeDataFilter[i];
                        if (item != null) {
                            var isFound = false;
                            if (item.title.indexOf(searchWord) != -1 || (item.deviceid && item.deviceid.toLowerCase().indexOf(searchWord) != -1)) {
                                copyItem = deepClone(item);
                                copyItem.expand = false;
                                isFound = true;
                            }
                            if (isFound == false && item.children && item.children.length > 0) {
                                // item.expand = true;
                                // childTemp.push(item);
                                var rs = that.variableDeepSearch(item.children, searchWord, limitcount);
                                if (rs && rs.length > 0) {
                                    copyItem = deepClone(item);
                                    copyItem.children = rs;
                                    copyItem.expand = true;
                                    isFound = true;
                                }
                            }

                            if (isFound == true) {
                                limitcount++;

                                childTemp.push(copyItem);
                                if (limitcount > 10) {
                                    break;
                                }
                            }
                        }
                    }

                    return childTemp;
                },
                queryEmployees: function(userName) {
                    var me = this;
                    var url = myUrls.queryEmployees();
                    me.loading = true;
                    utils.sendAjax(url, {
                        creater: this.createrToUser,
                        keyword: this.sosoTableValue,
                    }, function(resp) {
                        me.tableData = resp.employees;
                        me.loading = false;
                    });
                },
                getUserInfoList: function() {
                    var url = myUrls.queryUser();
                    utils.sendAjax(url, {
                        username: userName
                    }, this.doUserInfoList);
                },
                doUserInfoList: function(resp) {
                    var me = this;
                    var list = [];
                    if (resp.status == 0 && resp.userlists != null) {

                        resp.userlists.forEach(function(item) {
                            if (item.usertype < 4) {
                                list.push(item.username)
                            }
                        });
                    }
                    list.unshift(userName)
                    me.list = list;
                    me.userlists = list;
                },
            },
            watch: {
                isShowMatchDev: function() {
                    if (!this.isShowMatchDev) {
                        this.iconState = "ios-arrow-down";
                    } else {
                        this.iconState = "ios-arrow-up";
                    }
                },
                sosoValue: function(value) {
                    var me = this;
                    if (this.timeoutIns != null) {
                        clearTimeout(this.timeoutIns);
                    };

                    this.timeoutIns = setTimeout(function() {
                        me.filterMethod(value);
                    }, 300);
                },
            },
            computed: {
                modalTitle: function() {
                    return this.isEdit ? vRoot.$t('monitor.edit') : vRoot.$t('user.add');
                }
            },
            mounted: function() {
                var me = this;
                me.timeoutIns = null;
                me.getUserInfoList();
                me.queryUsersTree(function(usersTree) {
                    me.groupslist = usersTree;
                    me.treeData = usersTree;
                });
                me.queryEmployees();
                me.calcTableHeight();
                window.onresize = function() {
                    me.calcTableHeight();
                }
            }
        })
    </script>
</div>